const app = getApp()
import { request } from "../../request/index";
import { formatTime } from "../../utils/util";
Page({
  data: {
    number:[],
    isStartGame:true,
    isGameRule:false,
    time:0,
    timer:null,
    resultNum:[],
    gameEnd:false,
    tips:'',
    answer:[],
    resulTips:'苏苏',
    isActive:'',
    userInfo:{},
    preTime:null,
    preStartTime:3,
    isStartTime:false,
    isHistory:false,
    history:[],
    isRanking:false,
    onRankingList:[],
    offRankingList:[]
  },
  onLoad(){
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo
    })
  },
  // 每次点击触发的
  handleNumber(e){
    let {number} = e.currentTarget.dataset;
    let {index} = e.currentTarget.dataset;
    this.data.resultNum.push(number);
    this.setData({
      isActive:index
    })
    if(this.data.resultNum.length === 9){
      clearInterval(this.data.timer);

      let {number} = this.data;
      number.sort((a,b) => a - b)

      this.setData({
        gameEnd:true,
        resultNum:this.data.resultNum,
        answer:number
      })
      // 判断输赢
      let sum = 0;
      this.data.resultNum.forEach((v,i) => {
        if(v !== this.data.answer[i]) return sum++
      });
      if(sum === 0){
        this.setData({
          resulTips:'成 功'
        })
        wx.showToast({
          title: '真聪明~',
        })
      }else{
        this.setData({
          resulTips:'失 败'
        })
        wx.showToast({
          title: '小学重修~',
          icon:'error'
        });
      }
      // 判断用时给予不同提示
      if(this.data.time < 10) this.setData({
        tips:'天啦撸你可真是风一样的男子'
      })
      if(this.data.time > 15) this.setData({
        tips:'还不速速分手挽留手速~'
      })
      let dataTime = formatTime(new Date());
      let historyStorage = wx.getStorageSync('history') || [];
      let {answer,resultNum,resulTips} = this.data;
      let time = parseFloat(this.data.time.toFixed(2))
      let history = [{time,answer,resultNum,resulTips,dataTime},...historyStorage];
      wx.setStorageSync('history', history);
      let {avatarUrl,nickName} = this.data.userInfo
      // let requestRanking = [{time,avatarUrl,nickName,dataTime}];
      // 存入数据库的      
      if(this.data.resulTips !== '失 败' && this.data.userInfo.avatarUrl) request({
          url:'gameRecord',
          method:'POST',
          data:{"score":time,"avatarUrl":avatarUrl,"nickName":nickName,"dataTime":dataTime}
        });
    }
  },
  // 开始游戏
  startGame(){
    this.prepareTime();
    this.setData({
      number:[],
      resultNum:[],
      answer:[],
      time:0,
      isActive:'',
      tips:'平平无奇~',
      isStartGame:false,
      preStartTime:3,
      gameEnd:false,
    })
    this.randomNumber()
    setTimeout(() => {
      this.setData({
        isStartTime:false,
        time:this.data.time += 1
      })
      clearInterval(this.data.timer);
      this.data.timer = setInterval(() => {
        this.setData({
          time:this.data.time += 0.01
        })
      }, 10);
    }, 3000);
  },
  // 是否显示游戏规则
  gameRule(){
    this.setData({
      isGameRule:!this.data.isGameRule
    })
  },
  // 准备开始游戏
  prepareTime(){
    this.setData({
      isStartTime:true
    })
    let countDown = 1;
    clearInterval(this.data.preTime);
    this.data.preTime = setInterval(() => {
      if(countDown === 3){
        clearInterval(this.data.preTime);
      }
      this.setData({
        preStartTime:this.data.preStartTime - 1,
      })
      countDown++
    },1000);
  },
  // 随机获取九个数字
  randomNumber(){
    let sum = []
    while(sum.length < 9){
      let num = parseInt(Math.random() * 100) +1
      if (sum.indexOf(num) == -1) sum.push(num)
    }
    this.setData({
      number:sum
    })
  },
  // 获取用户信息设置头像
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        this.setData({
          userInfo:res.userInfo
        })
        console.log(res);
        wx.setStorageSync('userInfo', res.userInfo);
        this.startGame()
      },
    })
  },
  // 关闭结算
  close(){
    this.setData({
      gameEnd:false,
      isStartGame:true
    })
  },
  // 查看历史记录
  history(){
    this.setData({
      isHistory:!this.data.isHistory
    })
    let history = wx.getStorageSync('history') || [];
    this.setData({
      history
    })
  },
  // 查看排行
  async lookRanking(){
    if(!this.data.userInfo.avatarUrl) return wx.showToast({
      title: '请先登录！',
      icon:'error'
    })
    this.setData({
      onRankingList:[],
      offRankingList:[],
    })
    const {data} = await request({
      url:'getRecord',
    });
    data.forEach((v,i) => {
      if(i < 3) this.data.onRankingList.push(v)
      else this.data.offRankingList.push(v)
    })
    this.setData({
      isRanking:true,
      onRankingList:this.data.onRankingList,
      offRankingList:this.data.offRankingList
    })
  },
  // 关闭天梯榜
  closeRanking(){
    this.setData({
      isRanking:false
    })
  }
})
